var coupon={};
var couponId="";
var couponMsg="";
var editFlag=0;
var flag=1;
var biid="";
$(document).ready(function() {
    if(getStorage("couponMsg")){
        couponMsg=JSON.parse(getStorage("couponMsg"));
        couponId=couponMsg.couponId;
        editFlag=1;
        clearStorage("couponMsg");
    }
    accept();
    basic();
});
//保存
$("#saveCoupon").click(function(){
    if(editFlag===0){
        submit("coupon/addCouponBusiness");
    }else{
        submit("coupon/updateCouponBusiness");
    }
});
//编辑优惠券
function editCoupon(couponMsg){
    $("#connectShop").attr("data-biid",couponMsg.businessId).val(couponMsg.businessName).attr("disabled","disabled");
    $("#couponName").val(couponMsg.couponName);
    $("#couponDescribe").val(couponMsg.couponDescribe);
    $("#couponCategories").val(couponMsg.couponTypeId);
    $("#couponStart").val(timeStamp2String(couponMsg.couponStartTime, "ymdhms")).attr("disabled","disabled");
    $("#couponEnd").val(timeStamp2String(couponMsg.couponEndTime, "ymdhms")).attr("disabled","disabled");
    $("#couponCount").val(couponMsg.couponSendTotalQuantity);
    $("#couponLimit").val(couponMsg.couponObtainQuantityLimit);
    $("#couponAmount").val(couponMsg.couponAmount).attr("disabled","disabled");
    $("#couponCondition").val(couponMsg.couponUseMinAmount).attr("disabled","disabled");
    $("#couponPlatform").val(couponMsg.couponApplyPlatformId);
    $("#couponCrowd").val(couponMsg.couponApplyCrowdId);
    $("#couponSort").val(couponMsg.couponBusinessSort);
    if(!isNULL(couponMsg.couponImageUrl)){
        $("#couponImg").attr("data-url",couponMsg.couponImageUrl).attr("src",changeImgUrl(couponMsg.couponImageUrl));
    }
}
//统计输入框信息
function statics(){
    coupon={};
    coupon.name=$("#couponName").val();
    coupon.describe=$("#couponDescribe").val();
    coupon.categories=$("#couponCategories").val();
    coupon.businessId=$("#connectShop").attr("data-biid");
    coupon.startTime=$("#couponStart").val();
    coupon.endTime=$("#couponEnd").val();
    coupon.totalQuantity=$("#couponCount").val();
    coupon.limit=$("#couponLimit").val();
    coupon.amount=$("#couponAmount").val();
    coupon.condition=$("#couponCondition").val();
    coupon.platform=$("#couponPlatform").val();
    coupon.crowd=$("#couponCrowd").val();
    coupon.img=$("#couponImg").attr("data-url");
    coupon.sort=$("#couponSort").val();
}
//添加优惠券
function submit(url){
    if(flag!==1){
        layer.msg("请不要重复提交");
        return;
    }
    flag=0;
    statics();
    ajax({
        url:url,
        data:{
            couponId:couponId,
            businessId:coupon.businessId,
            // businessId:"8888888888",
            couponName:coupon.name,
            couponDescribe:coupon.describe,
            couponAmount:coupon.amount,
            couponStartTime:coupon.startTime,
            couponEndTime:coupon.endTime,
            couponTypeId:coupon.categories,
            couponImageUrl:coupon.img,
            // couponImageUrl:"/ptcent_file_upload/temp/2017-12-07/d5a82ef71183a4f31188e8cb3034.jpg",
            couponPropertyId:1,
            couponApplyCrowdId:coupon.crowd,
            couponUsableRangeId:2,
            couponUseMinAmount:coupon.condition,
            couponApplyPlatformId:coupon.platform,
            couponBusinessSort:coupon.sort,
            couponSendTotalQuantity:coupon.totalQuantity,
            couponObtainQuantityLimit:coupon.limit
        },
        success:function(data){
            
            if(data.success){
                layer.msg(data.message);
                window.location.href="coupon.html";
            }else{
                layer.msg(data.message);
                flag=1;
            }
        }
    });
}
//不含禁用选项
function handleBasic(id,list,listId,listContent){
    var html='';
    for(var i=0;i<list.length;i++){
        html+='<option value="'+list[i][listId]+'">'+list[i][listContent]+'</option>'
    }
    $("#"+id).html(html);
}
//含禁用选项
function handleType(id,list,listId,listContent){
    var html='';
    for(var i=0;i<list.length;i++){
        if(list[i][listId]===1){
            html+='<option value="'+list[i][listId]+'">'+list[i][listContent]+'</option>'
        }else{
            html+='<option value="'+list[i][listId]+'" disabled>'+list[i][listContent]+'</option>'
        }

    }
    $("#"+id).html(html);
}
//基本信息
function basic(){
    ajax({
        url:"coupon/queryCouponMultiTypeList",
        data:{},
        success:function(data){
            
            if(data.success){
                var crowdList=data.data.couponApplyCrowdList;
                handleBasic("couponCrowd",crowdList,"couponApplyCrowdId","couponApplyCrowdDesc");
                var platform=data.data.couponApplyPlatformList;
                handleType("couponPlatform",platform,"couponApplyPlatformId","couponAppyPlatformName");
                var typeList=data.data.couponTypeList;
                handleType("couponCategories",typeList,"couponTypeId","couponTypeName");
                if(editFlag===1){
                    editCoupon(couponMsg);
                }else if(getStorJson("airportInfo").biid!==""){
                    $("#connectShop").attr("data-biid",getStorJson("airportInfo").biid).val(getStorJson("airportInfo").biName).attr("disabled","disabled");
                }
            }else{
                layer.msg(data.message);
            }
        }
    });
}
//webUpload图片
function accept(){
    $list=$('#fileList');
    // 初始化Web Uploader
    var uploader = WebUploader.create({

        // 选完文件后，是否自动上传。
        auto: true,

        // 文件接收服务端。
        server: web_url_prefix+'upload/uploadJitesCmsImageMulit',

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: {
            id:'#filePicker',
            multiple:false
        },

        // 只允许选择图片文件。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpeg,image/png,image/jpg,image/bmp'
        }
    });

    //文件传输成功后的返回值
    uploader.on("uploadAccept",function(object,ret){
        $("#couponImg").attr("src",picPath+ret.avatar).attr("data-url",ret.avatar);
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress span');

        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<p class="progress"><span></span></p>')
                .appendTo( $li )
                .find('span');
        }

        $percent.css( 'width', percentage * 100 + '%' );
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on( 'uploadSuccess', function( file ) {
        $( '#'+file.id ).addClass('upload-state-done');
    });

    // 文件上传失败，显示上传出错。
    uploader.on( 'uploadError', function( file ) {
        var $li = $( '#'+file.id ),
            $error = $li.find('div.error');

        // 避免重复创建
        if ( !$error.length ) {
            $error = $('<div class="error"></div>').appendTo( $li );
        }

        $error.text('上传失败');
    });

// 完成上传完了，成功或者失败，先删除进度条。
    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').remove();
    });
}